from contextlib import contextmanager
from functools import wraps
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


# 创建对象的基类:
Base = declarative_base()
# 初始化数据库连接:
engine = create_engine('mysql+cymysql://root:Aa19950218!@nj-cynosdbmysql-grp-cn2j2vgz.sql.tencentcdb.com:26181/easymanage', pool_recycle=600)
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
db = DBSession()

def shutdown_session(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except:
            print('关闭数据库连接..')
            db.close()
            print('数据库回滚..')
            db.rollback()
        finally:
            print('关闭数据库连接..')
            db.close()
    return wrapper

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    session = DBSession()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()